import 'package:ladder_cash/app/app.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:ladder_cash/app/com/service/address_service.dart';
import 'package:ladder_cash/app/com/view/common_view.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/address_picker/locations_data.dart';
import 'package:flutter/material.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/more_pickers/route/single_picker_route.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/pickers.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/style/picker_style.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/time_picker/model/date_mode.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/time_picker/model/pduration.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/time_picker/model/suffix.dart';
import 'package:ladder_cash/app/com/view/flutter_pickers_master/time_picker/route/date_picker_route.dart';
import 'package:ladder_cash/gen/assets.gen.dart';
import 'package:ladder_cash/generated/assets.dart' as myAssets;
import 'package:ladder_cash/generated/l10n.dart';
import 'package:ladder_cash/value/app_colors.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';

import '../../../config/super_theme.dart';
import '../../page/component/common.dart';
import '../../page/component/decoration_bg.dart';

class MyDatePicker {
  void showDatePicker(context,
      {required onConfirm(txt, PDuration p),
      String? selectTxt,
      model = DateMode.YMD}) {
    // showMyDatePicker(context );
    // return;
    var selectDate = PDuration(day: 1, month: 1, year: 2000);
    if (selectTxt != null) {
      var splitTxt = selectTxt.contains('/') ? '/' : '-';
      var sels = selectTxt.split(splitTxt);
      if (sels.length == 3) {
        try {
          //日月年反填
          selectDate = PDuration(
              day: int.parse(sels[0]),
              month: int.parse(sels[1]),
              year: int.parse(sels[2]));

          // selectDate = PDuration(
          //     year: int.parse(sels[0]),
          //     month: int.parse(sels[1]),
          //     day: int.parse(sels[2]));
        } catch (e) {}
      }
    }
    Pickers.showDatePicker(
      context,
      mode: model,
      suffix: Suffix(),
      pickerStyle: PickerStyle(
          cancelButton: Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.only(left: 22, right: 12),
            child: Text(S.current.cancel,
                style: TextStyle(
                    color: Theme.of(context!).unselectedWidgetColor,
                    fontSize: 16.0)),
          ),
          commitButton: Container(
            alignment: Alignment.center,
            padding: const EdgeInsets.only(left: 12, right: 22),
            child: Text(S.current.confirm,
                style: TextStyle(
                    color: Theme.of(context!).primaryColor, fontSize: 16.0)),
          )),
      // minDate: PDuration(year: 2020, month: 2, day: 10),
      // maxDate: PDuration(second: 22),
      selectDate: selectDate,
      // minDate: PDuration(hour: 12, minute: 38, second: 3),
      // maxDate: PDuration(hour: 12, minute: 40, second: 36),
      onConfirm: (p) {
        print('longer >>> 返回数据：$p');
        var date = "";

        String hour = (p.hour ?? 0) >= 10 ? p.hour.toString() : "0${p.hour}";
        String minute =
            (p.minute ?? 0) >= 10 ? p.minute.toString() : "0${p.minute}";
        FocusManager.instance.primaryFocus?.unfocus();
        switch (model) {
          case DateMode.YMDHMS:
            date =
                '${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}';
            break;
          case DateMode.YMDHM:
            date = '${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}';
            break;
          case DateMode.YMDH:
            date = '${p.year}-${p.month}-${p.day} ${p.hour}';
            break;
          case DateMode.YMD:
            date = '${p.day}-${p.month}-${p.year}';
            // date = '${p.year}-${p.month}-${p.day}';
            break;
          case DateMode.YM:
            date = '${p.year}-${p.month}';
            break;
          case DateMode.Y:
            date = '${p.year}-${p.month}';
            break;
          case DateMode.MDHMS:
            date = '${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}';
            break;
          case DateMode.HMS:
            date = '${p.hour}:${p.minute}:${p.second}';
            break;
          case DateMode.HM:
            date = '$hour:$minute';
            break;
          case DateMode.MD:
            date = '${p.month}-${p.day}';
            break;
          case DateMode.S:
            date = '${p.second}';
            break;
        }
        FocusManager.instance.primaryFocus?.unfocus();
        Future.delayed(const Duration(milliseconds: 100)).then((v) {
          OldLInput.unfocus();
        });
        onConfirm(date, p);
      },
      // onChanged: (p) => print(p),
    );
  }

  static showSinglePicker(context,
      {required data, selectData, SingleCallback? onConfirm, title}) {
    showMySinglePicker(context,
        data: data, selectData: selectData, onConfirm: onConfirm, title: title);
    return;
    // Pickers.showSinglePicker(context,
    //     data: data,
    //     selectData: selectData,
    //     pickerStyle: PickerStyle(
    //         cancelButton: Container(
    //           alignment: Alignment.center,
    //           padding: const EdgeInsets.only(left: 22, right: 12),
    //           child: Text(S.current.cancel,
    //               style: TextStyle(
    //                   color: Theme.of(context!).unselectedWidgetColor,
    //                   fontSize: 16.0)),
    //         ),
    //         commitButton: Container(
    //           alignment: Alignment.center,
    //           padding: const EdgeInsets.only(left: 12, right: 22),
    //           child: Text(S.current.confirm,
    //               style: TextStyle(
    //                   color: Theme.of(context!).primaryColor, fontSize: 16.0)),
    //         )), onConfirm: (txt, i) {
    //   FocusManager.instance.primaryFocus?.unfocus();
    //   if (onConfirm != null) onConfirm(txt, i);
    // });
  }

  static Map<String, Map<String, String>>? addressData;

  static showAddressPicker(context, {onConfirm}) async {
    if (addressData == null || addressData!.length == 0) {
      List<dynamic> _addressData = await AddressService().getAddressData();
      addressData = {};
      for (dynamic d in _addressData) {
        addressData!['86'] ??= {}; //第一级
        String key = d['name'];
        String value = d['name'];
        addressData!['86']![key] = value;
        for (dynamic children in d['dictProvinceList']) {
          addressData![key] ??= {}; //第一级
          String chindKey = children['name'];
          String childValue = children['name'];
          addressData![key]![chindKey] = childValue;
        }
      }
      locations = addressData!;
      Address.provinces = locations['86']!.values.toList();
    }
// return;
    Pickers.showAddressPicker(context,
        addAllItem: false,
        pickerStyle: PickerStyle(
            cancelButton: Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 22, right: 12),
              child: Text('cancel',
                  style: TextStyle(
                      color: Theme.of(context!).unselectedWidgetColor,
                      fontSize: 16.0)),
            ),
            commitButton: Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 12, right: 22),
              child: Text('confirm',
                  style: TextStyle(
                      color: Theme.of(context!).primaryColor, fontSize: 16.0)),
            )), onConfirm: (txt, i, s) {
      FocusManager.instance.primaryFocus?.unfocus();
      if (onConfirm != null) onConfirm(txt, i);
    });
  }

  static showMySinglePicker(context,
      {required List data, selectData, SingleCallback? onConfirm, title}) {
    int _index = data.indexOf(selectData);
    // 选择器
    Widget cPicker = CupertinoPicker.builder(
      scrollController: FixedExtentScrollController(initialItem: _index),
      itemExtent: 50.w,
      useMagnifier: false,
      magnification: 1.2,
      selectionOverlay: null,
      onSelectedItemChanged: (int index) {
        _index = index;
      },
      childCount: data.length,
      itemBuilder: (_, index) {
        String text = data[index].toString();
        return Align(
            alignment: Alignment.center,
            child: Text(text,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 14.sp,
                ),
                textAlign: TextAlign.start));
      },
    );
    Get.dialog(Column(
      children: [
        Expanded(
          child: Container(),
        ),
        Column(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              height: 30.w,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  InkWell(
                    onTap: () {
                      Get.back();
                    },
                    child: Image.asset(
                      Assets.cer.cerClose.path,
                      width: 30.w,
                      height: 30.w,
                    ),
                  ),
                ],
              ),
            ),
            30.lsh,
            Container(
              margin: EdgeInsets.symmetric(horizontal: 20.w),
              padding: EdgeInsets.only(
                  bottom: 10.w, top: 10.w),
              height: 371.w,
              decoration: BoxDecoration(
                  image: getDecorationBg(Assets.cer.cerPanBg.path)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  textBorder(App.localeEn ? 'Select' : 'Seleccionar',
                      fontWeight: FontWeight.w900,
                      fontsize: 24.sp,
                      color: SuperTheme.textTitltPrimary,
                      borderColor: Colors.black,
                      fontFamily: 'italic'),
                  Stack(
                    children: [
                      Positioned(
                          width: 335.w,
                          top: 100.w,
                          child: Container(
                            height: 50.w,
                            decoration:
                            BoxDecoration(gradient: getGradient()),
                          )),
                      SizedBox(
                        width: 335.w,
                        child: cPicker,
                        height: 250.w,
                      ),

                    ],
                  ),
                  Container(
                      height: 46.w,
                      child: commonBtn(S.current.confirm, callback: () {
                        Get.back();
                        FocusManager.instance.primaryFocus?.unfocus();
                        String txt = data[_index];
                        if (onConfirm != null) onConfirm(txt, _index);
                      })),
                ],
              ),
            ),
          ],
        ),
        Expanded(child: Container())
      ],
    ));
    // CommonView.commDialog(
    //     children: [
    //       SizedBox(
    //         child: cPicker,
    //         height: 246.w,
    //       )
    //     ],
    //     title: App.localeEn?'Select':'Seleccionar',
    //     confirm: () {
    //       Get.back();
    //       FocusManager.instance.primaryFocus?.unfocus();
    //       String txt = data[_index];
    //       if (onConfirm != null) onConfirm(txt, _index);
    //     });
    // CommonView.commDialog(
    //     height:345.w,
    //     confirm: () {
    //
    //     },
    //     children: [
    //
    //     ],
    //   // bgImg: Assets.bgSingleSelectBg,
    //     title: title);
  }

  showPickDialog() {}

  static showMyDatePicker(context,
      {selectData, SingleCallback? onConfirm, title}) {
    // 选择器
    Widget cPicker = CupertinoDatePicker(
      itemExtent: 50.w,
      mode: CupertinoDatePickerMode.date,
      onDateTimeChanged: (dateTime) {},
    );
    CommonView.commDialog(
        confirm: () {
          Get.back();
          FocusManager.instance.primaryFocus?.unfocus();
        },
        children: [
          SizedBox(
            child: cPicker,
            height: 211.w,
          )
        ],
        title: title);
  }
}
